package com.yyz.controller;

import com.alibaba.fastjson.JSONObject;
import com.yyz.pojo.Contract;
import com.yyz.pojo.User;
import com.yyz.service.ContractService;
import com.yyz.tools.ExcelUtil;
import com.yyz.tools.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ContractController {

    @Autowired
    private ContractService contractService;
    /**
     * contract TODO(点击合同模块显示首页面信息)
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "contract.html", method = RequestMethod.GET)   //1
    public String contract(Model model, HttpSession session, @RequestParam(value = "type", required = false) String type) {
        Map<String, Object> map = new HashMap<String, Object>();
        User u = (User) session.getAttribute("USER_CODE");
        if (u != null) {
            if (u.getUserRole() != 1) {
                map.put("phone", u.getPhone());
            }
        }
        map.put("index", 0);
        map.put("size", 5);
        if (type != null && !"".equals(type)&& !"3".equals(type)) {
            map.put("type", type);
        }

        if ("3".equals(type)) {
            map.put("state","已完成");
        }
        Page<Contract> page = contractService.findByPage(map);
        model.addAttribute("page", page);
        model.addAttribute("type", type);
        return "billlist";
    }

    /**
     * queryContract TODO(点击查询合同数据)
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "contract.html", method = RequestMethod.POST)  //*1
    public String queryContract(
            Model model, HttpSession session,
            @RequestParam(value = "pageIndex", required = false) String pageIndex,
            @RequestParam(value = "businessCode", required = false) String businessCode,
            @RequestParam(value = "type", required = false) String type) {
        Map<String, Object> map = new HashMap<String, Object>();
        User u = (User) session.getAttribute("USER_CODE");
        if (u != null) {
            if (u.getUserRole() != 1) {
                map.put("phone", u.getPhone());
            }
        }
        if ("".equals(pageIndex) || null == pageIndex) {
            pageIndex = "1";
        }
        if (businessCode != null && !"".equals(businessCode)) {
            map.put("businessCode", businessCode);
        }
        if (type != null && !"".equals(type)&& !"3".equals(type)) {
            map.put("type", type);
        }
        if ("3".equals(type)) {
            map.put("state","已完成");
        }
        map.put("index", pageIndex);   //下一页之后pageIndex+1处理
        map.put("size", 5);
        Page<Contract> page = contractService.findByPage(map);
        model.addAttribute("businessCode", businessCode);
        model.addAttribute("type", map.get("type"));
        model.addAttribute("page", page);
        return "billlist";
    }

    /**
     * 检查数据是否存在
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "check.json", method = RequestMethod.GET)
    @ResponseBody
    public Object check(Model model
            , @RequestParam(value = "billid", required = false) String businessCode) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("businessCode1", businessCode);
        return contractService.countByQuery(map);
    }

    /**
     * 跳转到合同添加页面
     * @param model
     * @return
     */
    @RequestMapping(value = "billadd.html", method = RequestMethod.GET)
    public String billadd(Model model) {
        return "billadd";
    }

    /**
     * 跳转到合同详细页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "billview.html", method = RequestMethod.GET)
    public String billview(Model model,
                           @RequestParam(value = "billid", required = true) String billid) {
        Contract contract = contractService.queryById(Integer.parseInt(billid));
        model.addAttribute("bill", contract);
        return "billview";
    }

    /**
     * 跳转到合同更新页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "billmodify.html", method = RequestMethod.GET)
    public String billmodify(Model model,
                             @RequestParam(value = "billid", required = true) String billid) {
        Contract contract = contractService.queryById(Integer.parseInt(billid));
        model.addAttribute("bill", contract);
        return "billmodify";
    }
    /**
     * billmodify TODO(更新合同信息)
     *
     * @param model
     * @param contract
     * @param session
     * @return
     */
    @RequestMapping(value = "/billmodify.html", method = RequestMethod.POST)
    public String billmodify(Model model, Contract contract, HttpSession session) {
        Integer result = contractService.update(contract);
        if (result > 0) {
            return "redirect:contract.html";
        } else {
            return "billmodify";
        }
    }

    /**
     * providerdel TODO(通过ID删除对象)
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "billdel.json", method = RequestMethod.POST)
    @ResponseBody
    public Object billdel(Model model
            , @RequestParam(value = "billid", required = false) String billid) {
        JSONObject json = new JSONObject();
        Integer result = contractService.delete(Integer.parseInt(billid));
        if (result == 1) {
            json.put("delResult", "true");
        } else {
            json.put("delResult", "false");
        }
        return json;
    }

    /**
     * providerdel TODO(通过ID将对象设置完成)
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "success.json", method = RequestMethod.POST)
    @ResponseBody
    public Object success(Model model
            , @RequestParam(value = "billid", required = false) String billid) {
        JSONObject json = new JSONObject();
        Contract contract = new Contract();
        contract.setId(Long.parseLong(billid));
        contract.setState("已完成");
        Integer result = contractService.update(contract);
        if (result == 1) {
            json.put("delResult", "true");
        } else {
            json.put("delResult", "false");
        }
        return json;
    }



    /**
     * billAdd TODO(添加合同信息)
     *
     * @param model
     * @param contract
     * @param session
     * @return
     */
    @RequestMapping(value = "billAdd.html", method = RequestMethod.POST)
    public String providerAdd(Model model, Contract contract, HttpSession session) {
        Integer result = contractService.add(contract);
        if (result > 0) {
            return "redirect:contract.html";
        } else {
            return "billadd";
        }
    }

    @RequestMapping(value = "importExcel.json", method = RequestMethod.POST)
    @ResponseBody
    public Object importStorePriceExcel(MultipartFile file) {
        JSONObject json = new JSONObject();
        try {
            List<List<String>> excelList = ExcelUtil.readExcel(file.getInputStream(), 1);
            Contract contract;
            for (List<String> strings : excelList) {
                contract = new Contract();
                contract.setContractCode(strings.get(0));//合同号
                contract.setFlowCode(strings.get(1));//流水号
                contract.setEnterpriseName(strings.get(2));//企业名称
                contract.setAgent(strings.get(3));//经办人
                contract.setPhone(strings.get(4));//电话
                contract.setBusinessCode(strings.get(5));//业务号
                contract.setInDate(strings.get(6));//入网时间
                if (strings.get(7) != null && !"".equals(strings.get(7))) {
                    String price = strings.get(7).replaceAll("\n", "").replaceAll("\t", "");
                    contract.setPrice(new BigDecimal(price));//月租金额
                }
                contract.setContractTerm(strings.get(8));//合同期限
                contract.setEndDate(strings.get(9));//到期日期
                contract.setPayment(strings.get(10));//付费方式
                contract.setBusinessType(strings.get(11));//业务类型
                contract.setBandwidth(strings.get(12));//宽带
                contract.setState(strings.get(13));//状态
                System.out.println(contract);
                // 检查是否重复
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("businessCode", strings.get(5));//业务号
                int result = contractService.countByQuery(map);
                if (result > 0) {
                    if (json.get("error") != null) {
                        json.put("error", json.get("error") + "," + strings.get(5));
                    } else {
                        json.put("error", strings.get(5));
                    }
                    continue;
                }
                contractService.add(contract);
            }
            json.put("result", "true");
        } catch (Exception e) {
            e.printStackTrace();
            json.put("result", "false");
        }
        return json;
    }
}
